/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml.timgiayto.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import xml.timgiayto.binding.comment.InfoComment;
import xml.timgiayto.binding.comment.InfoComments;
import xml.timgiayto.utils.XMLTools;
import xml.timgiayto.binding.info.Information;
import xml.timgiayto.utils.CommonUtils;
import xml.timgiayto.utils.DBUtils;

/**
 *
 * @author mrnghiep
 */
public class Controller extends HttpServlet {

    private static String xmlFile = "WEB-INF/information.xml";

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String action = request.getParameter("action");
            if ("insertComment".equals(action)) {
                String name = request.getParameter("name");
                String email = request.getParameter("email");
                String content = request.getParameter("content");
                String date = request.getParameter("date");
                String strInfoId = request.getParameter("infoId");
                int infoId = Integer.parseInt(strInfoId);

                // Declare Object InfoComment
                InfoComment infoComment = new InfoComment(name, email, content, date, infoId);
                // Call function to insert to database
                boolean result = DBUtils.createComment(infoComment);

                // Marshall file XML Comment
                // Get Comments from database
                InfoComments infoComments = DBUtils.getComments();
                String contextPath = getServletContext().getRealPath("/");
                XMLTools.marshallXML(infoComments, contextPath + CommonUtils.COMMENT_PATH);

                if (result) {
                    out.write("Gửi bình luận thành công!");
                } else {
                    out.write("Gửi bình luận không thành công!");
                }
            } else if ("delete".equals(action)) {
                String strId = request.getParameter("id");
                int id = Integer.parseInt(strId);

                // Delete database
                boolean resultDB = DBUtils.deleteInfo(id);

                // Delete xml file
                String contextPath = getServletContext().getRealPath("/");
                String fileInfoPath = contextPath + CommonUtils.INFORMATION_PATH;
                String fileCommentPath = contextPath + CommonUtils.COMMENT_PATH;
                try {
                    Document infoDoc = XMLTools.parseFileToDom(fileInfoPath);
                    XPath xpath = XMLTools.createXPath();

                    // Delete in information.xml
                    Node infoNode = (Node) xpath.evaluate("//information[id='" + id + "']", infoDoc, XPathConstants.NODE);
                    Node infoParent = infoNode.getParentNode();
                    infoParent.removeChild(infoNode);

                    XMLTools.transformDOMToFile(infoParent, fileInfoPath);

                    // Delte in comment.xml
                    Document commentDoc = XMLTools.parseFileToDom(fileCommentPath);
                    NodeList list = (NodeList) xpath.evaluate("//infoComment[infoId='" + id + "']", commentDoc, XPathConstants.NODESET);

                    Node commentParent = list.item(0).getParentNode();
                    for (int i = 0; i < list.getLength(); i++) {
                        Node commentNode = list.item(i);
                        commentParent.removeChild(commentNode);
                    }
                    XMLTools.transformDOMToFile(commentParent, fileCommentPath);


                    if (resultDB) {
                        out.write("Xóa thông tin thành công.");
                    } else {
                        out.write("Không thể xóa thông tin.");
                    }

                } catch (TransformerConfigurationException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                } catch (TransformerException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                } catch (XPathExpressionException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ParserConfigurationException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SAXException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if ("Login".equals(action)) {
                String email = request.getParameter("txtEmail");
                String password = request.getParameter("txtPassword");

                // Call function checkLogin
                boolean result = DBUtils.checkLogin(email, password);
                if (result) {
                    request.getSession().setAttribute("EMAILADMIN", email + "<br/><a href='Controller?action=Logout'>Đăng xuất</a>");
                } else {
                    response.sendRedirect(CommonUtils.ADMIN_LOGIN_PATH);
                }
                response.sendRedirect(CommonUtils.ADMIN_INFORMATION_PATH);
            } else if ("Logout".equals(action)) {
                HttpSession session = request.getSession();
                session.setAttribute("EMAILADMIN", null);
                response.sendRedirect(CommonUtils.INDEX_PATH);
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
